<template>
  <el-form ref="lfmRef" :model="lfm" :rules="rules" size="large">
    <!-- User type selection -->
    <el-form-item prop="userType" style="margin-left: 100px">
      <el-radio-group v-model="lfm.userType" size="large">
        <el-radio-button label="researcher">研究者</el-radio-button>
        <el-radio-button label="student">普通人员</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item prop="contactInfo">
      <el-input v-model="lfm.contactInfo" placeholder="用户名：admin / user">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="lfm.password" type="password" placeholder="密码：123456" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <!-- 验证码 -->
    <el-form-item prop="captcha">
      <el-input v-model="lfm.captcha" placeholder="请输入验证码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <key />
          </el-icon>
        </template>
        <template #suffix>
          <img
              :src="captchaUrl"
              @click="refresh"
              alt="验证码"
              class="captcha-image"
          />
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" @click="submitLogin">
      登录
    </el-button>
  </div>
</template>


<script setup lang="ts">
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { ref, onMounted, nextTick } from "vue";
import studentsApi from '@/api/StudentApi';
import jwtApi from '@/api/JwtApi';
import userNameApi from "@/api/UserNameApi";
import researchersApi from "@/api/ResearcherApi"
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

// 获取路由转发器
const router = useRouter();

// 当组件挂载结束之后调用
onMounted(() => {
  document.title = "植物表型数据管理系统";
});

// 登录数据模型
const lfmModel = ref({
  contactInfo: "",
  password: "",
  captcha: "",
  userType: "student",// 用户类型，默认为普通人员
});
const lfm = lfmModel;

// 表单实例
const lfmRef = ref<InstanceType<typeof ElForm> | null>(null);

// 提交登录
// 提交登录
const submitLogin = () => {
  if (lfmRef.value) {
    lfmRef.value.validate((valid) => {
      if (valid) {
        // 根据用户类型选择不同的API进行登录
        const loginApi = lfm.value.userType === 'researcher'
            ? researchersApi.login
            : studentsApi.login;

        loginApi(lfm.value).then((resp) => {
          if (resp.code == 200) {
            // 令牌放到token中
            jwtApi.save(resp.data);
            // 存储用户名
            userNameApi.save(lfm.value.contactInfo);
            // 存储用户类型
            localStorage.setItem('userType', lfm.value.userType);

            ElMessage({
              message: "登录成功",
              type: "success",
            });

            // 根据用户类型跳转到不同的首页 - 使用新的路由结构
            const homePath = lfm.value.userType === 'researcher' ? '/researcher/dashboard' : '/student/dashboard';
            router.push(homePath);
          } else {
            ElMessage({
              message: resp.msg,
              type: "error",
            });
          }
        }).catch(error => {
          ElMessage({
            message: "登录失败，请稍后重试",
            type: "error",
          });
        });
      }
    });
  }
}

// 验证码URL
const captchaUrl = ref("/api/users/captcha");

// 刷新验证码
// 刷新验证码
const refresh = () => {
  captchaUrl.value = "/api/users/captcha?id=" + Math.random();
};

const rules = ref({
  contactInfo: [{ required: true, message: "用户名不可为空" }],
  password: [{ required: true, message: "密码不可为空" }],
 /* captcha: [
    { required: true, message: "验证码不可为空" },
    { min: 4, max: 4, message: "验证码只能是4位" },
  ],*/
});

// 重置表单
async function resetForm() {
  await nextTick(); // 确保 DOM 更新完成
  if (lfmRef.value) {
    lfmRef.value.resetFields();
    refresh();
  }
}
</script>

<style scoped lang="scss">
@import "index";
</style>
